'use client';

import { useState } from 'react';
import { FamilyMember } from '../types/family';
import { convertToAncientNumber, convertDateToAncient } from '../types/ancientNumberMap';

interface ProfileViewProps {
  familyData: FamilyMember[];
  onDataUpdate: (data: FamilyMember[]) => void;
}

export default function ProfileView({ familyData, onDataUpdate }: ProfileViewProps) {
  const [selectedPersonId, setSelectedPersonId] = useState<string>('');
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState<FamilyMember | null>(null);

  const selectedPerson = familyData.find(p => p.id === selectedPersonId);

  const handleEdit = () => {
    if (selectedPerson) {
      setEditData({
        ...selectedPerson,
        // 确保性别字段有默认值，兼容旧数据
        gender: selectedPerson.gender || 'male',
        // 确保排名字段存在，兼容旧数据
        ranking: selectedPerson.ranking || ''
      });
      setIsEditing(true);
    }
  };

  const handleSave = () => {
    if (editData) {
      const updatedData = familyData.map(person =>
        person.id === editData.id ? editData : person
      );
      onDataUpdate(updatedData);
      setIsEditing(false);
      setEditData(null);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    setEditData(null);
  };

  const handleDelete = () => {
    if (selectedPerson && confirm(`确定要删除 ${selectedPerson.name} 的信息吗？`)) {
      // 检查是否有子女
      const hasChildren = familyData.some(p => p.parentId === selectedPerson.id);
      if (hasChildren) {
        alert('该成员有子女记录，无法删除。请先删除其子女记录。');
        return;
      }

      const updatedData = familyData.filter(person => person.id !== selectedPerson.id);
      onDataUpdate(updatedData);
      setSelectedPersonId('');
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    if (editData) {
      const { name, value, type } = e.target;
      setEditData({
        ...editData,
        [name]: type === 'number' ? parseInt(value) || 0 : value
      });
    }
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return '未填写';
    return convertDateToAncient(dateString);
  };

  const getParentName = (parentId: string | null) => {
    if (!parentId) return '无';
    const parent = familyData.find(p => p.id === parentId);
    return parent ? parent.name : '未知';
  };

  const getChildren = (personId: string) => {
    return familyData.filter(p => p.parentId === personId);
  };

  return (
    <div className="p-6">
      <h2 className="text-2xl font-bold text-secondary mb-6">个人信息管理</h2>

      {/* 选择人员 */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          选择族谱成员
        </label>
        <select
          value={selectedPersonId}
          onChange={(e) => setSelectedPersonId(e.target.value)}
          className="w-full max-w-md px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
        >
          <option value="">请选择成员</option>
          {familyData.map(person => (
            <option key={person.id} value={person.id}>
              {person.name} ({person.gender === 'male' ? '男' : '女'}) (第{convertToAncientNumber(person.generation)}世)
            </option>
          ))}
        </select>
      </div>

      {selectedPerson && (
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          {/* 操作按钮 */}
          <div className="flex justify-end space-x-3 mb-6">
            {!isEditing ? (
              <>
                <button
                  onClick={handleEdit}
                  className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
                >
                  编辑
                </button>
                <button
                  onClick={handleDelete}
                  className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition-colors"
                >
                  删除
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={handleSave}
                  className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors"
                >
                  保存
                </button>
                <button
                  onClick={handleCancel}
                  className="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 transition-colors"
                >
                  取消
                </button>
              </>
            )}
          </div>

          {isEditing && editData ? (
            /* 编辑模式 */
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                  <input
                    type="text"
                    name="name"
                    value={editData.name}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">性别</label>
                  <select
                    name="gender"
                    value={editData.gender}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  >
                    <option value="male">男</option>
                    <option value="female">女</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">世次</label>
                  <input
                    type="number"
                    name="generation"
                    value={editData.generation}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">排名</label>
                <div className="flex flex-wrap gap-4">
                  {(editData.gender === 'male' 
                    ? ['长子', '次子', '三子', '四子', '五子', '六子', '七子', '八子', '九子', '十子']
                    : ['长女', '次女', '三女', '四女', '五女', '六女', '七女', '八女', '九女', '十女']
                  ).map((rank) => (
                    <label key={rank} className="flex items-center space-x-2 cursor-pointer">
                      <input
                        type="radio"
                        name="ranking"
                        value={rank}
                        checked={editData.ranking === rank}
                        onChange={handleInputChange}
                        className="w-4 h-4 text-primary border-gray-300 focus:ring-primary focus:ring-2"
                      />
                      <span className="text-sm text-gray-700">{rank}</span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">出生年月日</label>
                  <input
                    type="date"
                    name="birthDate"
                    value={editData.birthDate}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">终年月日</label>
                  <input
                    type="date"
                    name="deathDate"
                    value={editData.deathDate}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">履历</label>
                <textarea
                  name="biography"
                  value={editData.biography}
                  onChange={handleInputChange}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">配偶姓名</label>
                  <input
                    type="text"
                    name="spouseName"
                    value={editData.spouseName}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">配偶出生年月日</label>
                  <input
                    type="date"
                    name="spouseBirthDate"
                    value={editData.spouseBirthDate}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">配偶终年月日</label>
                  <input
                    type="date"
                    name="spouseDeathDate"
                    value={editData.spouseDeathDate}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">配偶履历</label>
                <textarea
                  name="spouseBiography"
                  value={editData.spouseBiography}
                  onChange={handleInputChange}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>


              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

                <label className="block text-sm font-medium text-gray-700 mb-1">
                  住址
                </label>
                <p />
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    镇(市)
                  </label>
                  <input
                    type="text"
                    name="town"
                    value={editData.town}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    区(县或村)
                  </label>
                  <input
                    type="text"
                    name="county"
                    value={editData.county}
                    onChange={handleInputChange}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div>

                <label className="block text-sm font-medium text-gray-700 mb-1">备注</label>
                <textarea
                  name="notes"
                  value={editData.notes}
                  onChange={handleInputChange}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>

            </div>
          ) : (
            /* 查看模式 */
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h3 className="text-lg font-semibold text-gray-800 mb-3 border-b pb-2">基本信息</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  <div>
                    <span className="text-sm text-gray-600">姓名：</span>
                    <span className={`font-medium ${selectedPerson.gender === 'male' ? 'text-blue-600' : 'text-pink-600'}`}>
                      {selectedPerson.name}
                    </span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">性别：</span>
                    <span className={`font-medium ${selectedPerson.gender === 'male' ? 'text-blue-600' : 'text-pink-600'}`}>
                      {selectedPerson.gender === 'male' ? '男' : '女'}
                    </span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">世次：</span>
                    <span className="font-medium">第{convertToAncientNumber(selectedPerson.generation)}世</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">父母：</span>
                    <span className="font-medium">{getParentName(selectedPerson.parentId)}</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">排名：</span>
                    <span className="font-medium">{selectedPerson.ranking || '未填写'}</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">出生日期：</span>
                    <span className="font-medium">{formatDate(selectedPerson.birthDate)}</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">终年日期：</span>
                    <span className="font-medium">{formatDate(selectedPerson.deathDate)}</span>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">现在住址：</span>
                    <span className="font-medium">{selectedPerson.town + selectedPerson.county || '未填写'}</span>
                  </div>
                </div>
              </div>

              {/* 履历 */}
              {selectedPerson.biography && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-800 mb-3 border-b pb-2">履历</h3>
                  <p className="text-gray-700 whitespace-pre-wrap">{selectedPerson.biography}</p>
                </div>
              )}

              {/* 配偶信息 */}
              {selectedPerson.spouseName && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-800 mb-3 border-b pb-2">配偶信息</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div>
                      <span className="text-sm text-gray-600">配偶姓名：</span>
                      <span className={`font-medium ${selectedPerson.gender === 'male' ? 'text-pink-600' : 'text-blue-600'}`}>{selectedPerson.spouseName}</span>
                    </div>
                    <div>
                      <span className="text-sm text-gray-600">出生日期：</span>
                      <span className="font-medium">{formatDate(selectedPerson.spouseBirthDate)}</span>
                    </div>
                    <div>
                      <span className="text-sm text-gray-600">终年日期：</span>
                      <span className="font-medium">{formatDate(selectedPerson.spouseDeathDate)}</span>
                    </div>
                    
                  </div>
                  {selectedPerson.spouseBiography && (
                    <div className="mt-4">
                      <span className="text-sm text-gray-600">配偶履历：</span>
                      <p className="text-gray-700 whitespace-pre-wrap mt-1">{selectedPerson.spouseBiography}</p>
                    </div>
                  )}
                </div>
              )}

              {/* 子女信息 */}
              {(() => {
                const children = getChildren(selectedPerson.id);
                return children.length > 0 && (
                  <div>
                    <h3 className="text-lg font-semibold text-gray-800 mb-3 border-b pb-2">子女信息</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                      {children.map(child => (
                        <div key={child.id} className="bg-gray-50 p-3 rounded-md">
                          <div className="font-medium">{child.name}</div>
                          <div className="text-sm text-gray-600">第{convertToAncientNumber(child.generation)}世</div>
                          {child.birthDate && (
                            <div className="text-sm text-gray-600">生于 {formatDate(child.birthDate)}</div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })()}

              {/* 备注 */}
              {selectedPerson.notes && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-800 mb-3 border-b pb-2">备注</h3>
                  <p className="text-gray-700 whitespace-pre-wrap">{selectedPerson.notes}</p>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {!selectedPerson && (
        <div className="text-center py-12 text-gray-500">
          <p>请选择一个族谱成员查看详细信息</p>
        </div>
      )}
    </div>
  );
}